package com.piece.core.elasticsearch.support;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import com.piece.core.elasticsearch.properties.ElasticsearchProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
//import org.elasticsearch.client.RestHighLevelClient;

@Slf4j
public class ESClientPool {

    private EsClientPoolFactory factory;
    private GenericObjectPool<ElasticsearchClient> clientPool;

    public ESClientPool(EsClientPoolFactory clientPoolFactory) {
        this.factory = clientPoolFactory;

        ElasticsearchProperties properties = factory.getElasticsearchProperties();
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(properties.getMaxConnectTotal());
        config.setMaxTotal(properties.getMaxConnectPerRoute());
        this.clientPool = new GenericObjectPool<>(factory, config);
    }

    public ElasticsearchClient getSyncClient() throws Exception {
        ElasticsearchClient client = clientPool.borrowObject();
        return client;
    }

    public ElasticsearchClient getClient() throws Exception {
        ElasticsearchClient client = clientPool.borrowObject();
        return client;
    }

    public void returnClient(ElasticsearchClient client) throws Exception {
        clientPool.returnObject(client);
    }
}
